import React, {FC,MouseEvent}  from "react";
import styles from "./EditCanvas.module.scss"
// // 临时静态展示一下 Title Input 的效果
// import QuestionTitle from "../../../components/QuestionEdit/QuestionTitle/Compent";
// import QuestionInput from "../../../components/QuestionEdit/QuestionInput/Compent";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import {getComponentConfByType} from "../../../components/QuestionEdit";
import {changeSelectedId, ComponentInfoType} from "../../../store/componentsReducer";
import {useDispatch} from "react-redux";
import classNames from "classnames";
type PropsType = {
    loading: boolean
}

function genComponent(componentInfo: ComponentInfoType) {
    const { type, props } = componentInfo // 每个组件的信息，是从 redux store 获取的（服务端获取）

    const componentConf = getComponentConfByType(type)
    if (componentConf == null) return null

    const { Component } = componentConf
    return <Component {...props} />
}


const EditCanvas:FC<PropsType> = ({loading}) => {

    const dispatch = useDispatch()
    // 点击组件，选中




    const { componentList,selectedId='' } = useGetComponentInfo();

    function handleClick(event: MouseEvent, id: string) {
        event.stopPropagation() // 阻止冒泡
        dispatch(changeSelectedId(id));
    }

    return (
        <div className={styles.canvas}>

            {componentList.map(c=>{
                const {fe_id} =c;
                // console.log(fe_id+"???");
                // 拼接 class name
                const wrapperDefaultClassName = styles['component-wrapper']
                const selectedClassName = styles.selected
                const lockedClassName = styles.locked
                const wrapperClassName = classNames({
                    [wrapperDefaultClassName]: true,
                    [selectedClassName]: fe_id === selectedId,
                    // [lockedClassName]: isLocked,
                })
                console.log(selectedId +"??"+fe_id)

                return(
                    <div key={fe_id} className={wrapperClassName} onClick={(e) => handleClick(e, fe_id)}>
                        <div className={styles.component}>{genComponent(c)}</div>
                    </div>
                );
            })}

            {/* <div className={styles["component-wrapper"]}>*/}
            {/*    <div className={styles.component}>*/}
            {/*        <QuestionTitle/>*/}
            {/*    </div>*/}
            {/* </div>*/}

            {/*<div className={styles["componentWrapper"]}>*/}
            {/*        <div className={styles.component}>*/}
            {/*            <QuestionInput/>*/}
            {/*        </div>*/}
            {/*</div>*/}

        </div>
    );
}

export default EditCanvas;